﻿using Model.Parameter.Admin;
using System.Linq.Expressions;
using Utils.Extensions;

namespace Service.Base
{
    /// <summary>
    /// 业务层基类 实体继续ModelBase
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseService<T> : IBaseService<T> where T : ModelBase, new()
    {
        public IUnitOfWorkService _UnitOfWorkService;

        private ISqlSugarClient _db = null;

        public BaseService(IUnitOfWorkService unitOfWorkService)
        {
            _UnitOfWorkService = unitOfWorkService;
        }

        private TAdminInfo _cs = null;

        public TAdminInfo _CurrentAdmin
        {
            get
            {
                var json = _UnitOfWorkService.GetAdminJwt();
                if (!string.IsNullOrEmpty(json))
                {
                    _cs = Newtonsoft.Json.JsonConvert.DeserializeObject<TAdminInfo>(json);
                }
                else
                {
                    _cs = null;
                }
                return _cs;
            }
            private set { }
        }

        private TCustomerinfo _cu = null;

        public TCustomerinfo _CurrentCustomer
        {
            get
            {
                var json = _UnitOfWorkService.GetCustomerJwt();
                if (!string.IsNullOrEmpty(json))
                {
                    _cu = Newtonsoft.Json.JsonConvert.DeserializeObject<TCustomerinfo>(json);
                }
                else
                {
                    _cu = null;
                }
                return _cu;
            }
            private set { }
        }

        public ISqlSugarClient _DbContext
        {
            get
            {
                _db ??= _UnitOfWorkService.GetDbContext();
                return _db;
            }
            private set { }
        }

        private IResultHelperService _rh = null;

        public IResultHelperService _ResultHelper
        {
            get
            {
                _rh ??= _UnitOfWorkService.GetResultHeplper();
                return _rh;
            }
            private set { }
        }

        private IRedisService _rd = null;

        public IRedisService _Redis
        {
            get
            {
                _rd ??= _UnitOfWorkService.GetRedisConn();
                return _rd;
            }
            private set { }
        }

        private IEnumHelperService _en = null;

        public IEnumHelperService _EnumHelper
        {
            get
            {
                _en ??= _UnitOfWorkService.GetEnumHelper();
                return _en;
            }
            private set { }
        }

        #region 公共操作

        /// <summary>
        /// 返回一个实体
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public virtual async Task<RM_ApiResult> GetItem(int Key)
        {
            if (await Any(Key))
            {
                return _ResultHelper.BuildSuccess(await Get(Key));
            }
            else
            {
                return _ResultHelper.BuildError(Enum_SysAttributeType.Misc.NoData);
            }
        }

        /// <summary>
        /// 返回一个分页列表
        /// </summary>
        /// <param name="exp"></param>
        /// <param name="par"></param>
        /// <param name="expression"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<RM_PageReturn<T>> GetPageByExp(Expression<Func<T, bool>> exp, Par_AdminPageBase par, Expression<Func<T, object>> expression, OrderByType type = OrderByType.Asc)
        {
            var datas = new RM_PageReturn<T>
            {
                TotalCount = await Count(exp)
            };
            if (par != null)
            {
                datas.Datas = await _DbContext.Queryable<T>().Where(exp).OrderBy(expression, type).ToPageListAsync(par.PageNo, par.PageSize);
                datas.PageSize = par.PageSize;
                datas.PageNo = par.PageNo;
            }
            else
            {
                datas.Datas = await _DbContext.Queryable<T>().Where(exp).OrderBy(expression, type).ToListAsync();
                datas.PageSize = datas.Datas.Count;
                datas.PageNo = 1;
            }
            return datas;
        }

        /// <summary>
        /// 新增或修改
        /// </summary>
        /// <param name="par"></param>
        /// <param name="NeedKey"></param>
        /// <param name="addLimit"></param>
        /// <param name="updateLimit"></param>
        /// <returns></returns>
        public async Task<int> AddOrUpdate(T par, bool NeedKey = false, Expression<Func<T, bool>> addLimit = null, Expression<Func<T, bool>> updateLimit = null)
        {
            if (par.Id == 0)
            {
                if (addLimit != null && await Any(addLimit)) return -1;
                if (NeedKey)
                {
                    return await AddRId(par);
                }
                else
                {
                    return await Add(par);
                }
            }
            else
            {
                if (updateLimit != null && await Any(updateLimit)) return -1;
                var result = await Update(par);
                if (NeedKey)
                {
                    if (result == 0) return result;
                    else
                    {
                        return par.Id;
                    }
                }
                else
                {
                    return result;
                }
            }
        }

        /// <summary>
        /// 批量新增或修改
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <param name="Key"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public async Task<RM_ApiResult> Status<T1>(int Key, int status) where T1 : ModelStatusBase, new()
        {
            await Update<T1>(Key, o => new T1 { Status = status });

            return _ResultHelper.BuildActionSuccess();
        }

        /// <summary>
        /// 删除一个
        /// </summary>
        /// <param name="Key"></param>
        /// <returns></returns>
        public virtual async Task<RM_ApiResult> DeleteItem(int Key)
        {
            await Delete(Key);
            return _ResultHelper.BuildActionSuccess();
        }

        /// <summary>
        /// 删除多个
        /// </summary>
        /// <param name="Keys"></param>
        /// <returns></returns>
        public virtual async Task<RM_ApiResult> DeleteByKeys(List<int> Keys)
        {
            await Delete(Keys);
            return _ResultHelper.BuildActionSuccess();
        }

        public async Task<RM_PageReturn<T1>> GetOtherPageByExp<T1>(Expression<Func<T1, bool>> exp, Par_AdminPageBase par, Expression<Func<T1, object>> expression, OrderByType type = OrderByType.Asc) where T1 : ModelBase, new()
        {
            var datas = new RM_PageReturn<T1>
            {
                TotalCount = await Count(exp)
            };
            if (par != null)
            {
                datas.Datas = await _DbContext.Queryable<T1>().Where(exp).OrderBy(expression, type).ToPageListAsync(par.PageNo, par.PageSize);
                datas.PageSize = par.PageSize;
                datas.PageNo = par.PageNo;
            }
            else
            {
                datas.Datas = await _DbContext.Queryable<T1>().Where(exp).OrderBy(expression, type).ToListAsync();
                datas.PageSize = datas.Datas.Count;
                datas.PageNo = 1;
            }
            return datas;
        }

        public async Task<RM_PageReturn<T>> GetPageHasInclueByExp(Expression<Func<T, bool>> exp, Par_AdminPageBase par, Expression<Func<T, object>> include, Expression<Func<T, object>> expression, OrderByType type = OrderByType.Asc)
        {
            var datas = new RM_PageReturn<T>
            {
                TotalCount = await Count(exp)
            };
            if (par != null)
            {
                datas.Datas = await _DbContext.Queryable<T>().Includes(include).Where(exp).OrderBy(expression, type).ToPageListAsync(par.PageNo, par.PageSize);
                datas.PageSize = par.PageSize;
                datas.PageNo = par.PageNo;
            }
            else
            {
                datas.Datas = await _DbContext.Queryable<T>().Includes(include).Where(exp).OrderBy(expression, type).ToListAsync();
                datas.PageSize = datas.Datas.Count;
                datas.PageNo = 1;
            }
            return datas;
        }

        #endregion 公共操作

        /// <summary>
        /// 数据库连接
        /// </summary>
        public ISqlSugarClient Db => _DbContext;

        #region 新增

        /// <summary>
        /// 批量添加实体
        /// </summary>
        /// <param name="entities">要添加的实体列表</param>
        /// <returns>受影响的行数</returns>
        public virtual async Task<int> Add(List<T> entities)
        {
            entities = SetCreaterAndUpdaterId(entities);
            return await Db.Add(entities);
        }

        /// <summary>
        /// 添加单个实体
        /// </summary>
        /// <param name="entity">要添加的实体</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> Add(T entity)
        {
            entity = SetCreaterAndUpdaterId(entity);
            return await Db.Add(entity);
        }

        /// <summary>
        /// 添加实体并返回新增的实体对象
        /// </summary>
        /// <param name="entity">要添加的实体</param>
        /// <returns>新增的实体对象</returns>
        public virtual async Task<T> AddREntity(T entity)
        {
            entity = SetCreaterAndUpdaterId(entity);
            return await Db.AddREntity(entity);
        }

        /// <summary>
        /// 添加实体并返回自增ID
        /// </summary>
        /// <param name="entity">要添加的实体</param>
        /// <returns>自增ID</returns>
        public virtual async Task<int> AddRId(T entity)
        {
            entity = SetCreaterAndUpdaterId(entity);
            return await Db.AddRId(entity);
        }

        #endregion 新增

        #region 新增2

        /// <summary>
        /// 批量添加实体
        /// </summary>
        /// <param name="entities">要添加的实体列表</param>
        /// <returns>受影响的行数</returns>
        public virtual async Task<int> Add<T2>(List<T2> entities) where T2 : ModelBase, new()
        {
            entities = SetCreaterAndUpdaterId(entities);
            return await Db.Add(entities);
        }

        /// <summary>
        /// 添加单个实体
        /// </summary>
        /// <param name="entity">要添加的实体</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> Add<T2>(T2 entity) where T2 : ModelBase, new()
        {
            entity = SetCreaterAndUpdaterId(entity);
            return await Db.Add(entity);
        }

        /// <summary>
        /// 添加实体并返回新增的实体对象
        /// </summary>
        /// <param name="entity">要添加的实体</param>
        /// <returns>新增的实体对象</returns>
        public virtual async Task<T2> AddREntity<T2>(T2 entity) where T2 : ModelBase, new()
        {
            entity = SetCreaterAndUpdaterId(entity);
            return await Db.AddREntity(entity);
        }

        /// <summary>
        /// 添加实体并返回自增ID
        /// </summary>
        /// <param name="entity">要添加的实体</param>
        /// <returns>自增ID</returns>
        public virtual async Task<int> AddRId<T2>(T2 entity) where T2 : ModelBase, new()
        {
            entity = SetCreaterAndUpdaterId(entity);
            return await Db.AddRId(entity);
        }

        #endregion 新增2

        #region 删除

        /// <summary>
        /// 根据ID删除实体
        /// </summary>
        /// <param name="id">实体的ID</param>
        /// <returns>如果删除成功返回true，否则返回false</returns>
        public async Task<bool> Delete(int id)
        {
            return await Db.Delete<T>(id);
        }

        /// <summary>
        /// 根据ID列表删除实体
        /// </summary>
        /// <param name="ids">实体的ID列表</param>
        /// <returns>如果删除成功返回true，否则返回false</returns>
        public virtual async Task<bool> Delete(List<int> ids)
        {
            return await Db.Delete<T>(ids);
        }

        /// <summary>
        /// 根据条件表达式删除实体
        /// </summary>
        /// <param name="whereExpression">删除条件表达式</param>
        /// <returns>如果删除成功返回true，否则返回false</returns>
        public virtual async Task<bool> Delete(Expression<Func<T, bool>> whereExpression)
        {
            return await Db.Delete(whereExpression);
        }

        /// <summary>
        /// 根据SQL语句删除实体
        /// </summary>
        /// <param name="sql">删除的SQL语句</param>
        /// <returns>如果删除成功返回true，否则返回false</returns>
        public virtual async Task<bool> DeleteSql(string sql)
        {
            return await TryExtensions.Trycatch(() => Db.Ado.ExecuteCommandAsync(sql)) > 0;
        }

        #endregion 删除

        #region 删除2

        /// <summary>
        /// 根据ID删除实体
        /// </summary>
        /// <param name="id">实体的ID</param>
        /// <returns>如果删除成功返回true，否则返回false</returns>
        public virtual async Task<bool> Delete<T2>(int id) where T2 : ModelBase, new()
        {
            return await Db.Delete<T2>(id);
        }

        /// <summary>
        /// 根据ID列表删除实体
        /// </summary>
        /// <param name="ids">实体的ID列表</param>
        /// <returns>如果删除成功返回true，否则返回false</returns>
        public virtual async Task<bool> Delete<T2>(List<int> ids) where T2 : ModelBase, new()
        {
            return await Db.Delete<T2>(ids);
        }

        /// <summary>
        /// 根据条件表达式删除实体
        /// </summary>
        /// <param name="whereExpression">删除条件表达式</param>
        /// <returns>如果删除成功返回true，否则返回false</returns>
        public virtual async Task<bool> Delete<T2>(Expression<Func<T2, bool>> whereExpression) where T2 : ModelBase, new()
        {
            return await Db.Delete(whereExpression);
        }

        #endregion 删除2

        #region 查询

        /// <summary>
        /// 根据ID获取单个实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual async Task<T> Get(int id)
        {
            return await Db.Get<T>(id);
        }

        /// <summary>
        /// 根据条件表达式获取单个实体
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public virtual async Task<T> Get(Expression<Func<T, bool>> whereExpression = null)
        {
            return await Db.Get<T>(whereExpression);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public virtual async Task<int> Count(Expression<Func<T, bool>> whereExpression = null)
        {
            return await Db.Count<T>(whereExpression);
        }

        /// <summary>
        /// 根据条件表达式获取实体列表
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public virtual async Task<List<T>> GetList(Expression<Func<T, bool>> whereExpression = null)
        {
            return await Db.GetList<T>(whereExpression);
        }

        /// <summary>
        /// 根据SQL语句获取实体列表
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public virtual async Task<List<T>> GetList(string sql)
        {
            return await Db.GetList<T>(sql);
        }

        /// <summary>
        /// 是否存在这条记录
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public virtual async Task<bool> Any(Expression<Func<T, bool>> whereExpression = null)
        {
            return await Db.Any<T>(whereExpression);
        }

        /// <summary>
        /// 根据ID判断记录是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual async Task<bool> Any(int id)
        {
            return await Any(u => u.Id == id);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderByType"></param>
        /// <returns></returns>
        public virtual async Task<(List<T>, int, int)> Page(Expression<Func<T, bool>> expression = null, int pageIndex = 1, int pageSize = 15,
            Expression<Func<T, object>> orderBy = null, OrderByType orderByType = OrderByType.Asc)
        {
            return await Db.Page<T>(expression, pageIndex, pageSize, orderBy, orderByType);
        }

        /// <summary>
        /// 根据SQL分页查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderByType"></param>
        /// <returns></returns>
        public virtual async Task<(List<T>, int, int)> Page(string sql = null, int pageIndex = 1, int pageSize = 15,
            Expression<Func<T, object>> orderBy = null, OrderByType orderByType = OrderByType.Asc)
        {
            return await Db.Page<T>(sql, pageIndex, pageSize, orderBy, orderByType);
        }

        #endregion 查询

        #region 查询2

        /// <summary>
        /// 根据ID获取单个实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual async Task<T2> Get<T2>(int id) where T2 : ModelBase, new()
        {
            return await Db.Get<T2>(id);
        }

        /// <summary>
        /// 根据条件表达式获取单个实体
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public virtual async Task<T2> Get<T2>(Expression<Func<T2, bool>> whereExpression = null) where T2 : ModelBase, new()
        {
            return await Db.Get(whereExpression);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public virtual async Task<int> Count<T2>(Expression<Func<T2, bool>> whereExpression = null) where T2 : ModelBase, new()
        {
            return await Db.Count(whereExpression);
        }

        /// <summary>
        /// 根据条件表达式获取实体列表
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public virtual async Task<List<T2>> GetList<T2>(Expression<Func<T2, bool>> whereExpression = null) where T2 : ModelBase, new()
        {
            return await Db.GetList(whereExpression);
        }

        /// <summary>
        /// 根据SQL语句获取实体列表
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public virtual async Task<List<T2>> GetList<T2>(string sql) where T2 : ModelBase, new()
        {
            return await Db.GetList<T2>(sql);
        }

        /// <summary>
        /// 是否存在这条记录
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public virtual async Task<bool> Any<T2>(Expression<Func<T2, bool>> whereExpression = null) where T2 : ModelBase, new()
        {
            return await Db.Any(whereExpression);
        }

        /// <summary>
        /// 根据ID判断记录是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual async Task<bool> Any<T2>(int id) where T2 : ModelBase, new()
        {
            return await Any<T2>(u => u.Id == id);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderByType"></param>
        /// <returns></returns>
        public virtual async Task<(List<T2>, int, int)> Page<T2>(Expression<Func<T2, bool>> expression = null, int pageIndex = 1, int pageSize = 15,
            Expression<Func<T2, object>> orderBy = null, OrderByType orderByType = OrderByType.Asc) where T2 : ModelBase, new()
        {
            return await Db.Page(expression, pageIndex, pageSize, orderBy, orderByType);
        }

        /// <summary>
        /// 根据SQL分页查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderByType"></param>
        /// <returns></returns>
        public virtual async Task<(List<T2>, int, int)> Page<T2>(string sql = null, int pageIndex = 1, int pageSize = 15,
            Expression<Func<T2, object>> orderBy = null, OrderByType orderByType = OrderByType.Asc) where T2 : ModelBase, new()
        {
            return await Db.Page(sql, pageIndex, pageSize, orderBy, orderByType);
        }

        #endregion 查询2

        #region 查询3

        /// <summary>
        /// 根据ID获取单个实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual async Task<V> Get<T2, V>(int id) where T2 : ModelBase, new()
        {
            return await Db.Get<T2, V>(id);
        }

        /// <summary>
        /// 根据条件表达式获取单个实体
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public virtual async Task<V> Get<T2, V>(Expression<Func<T2, bool>> whereExpression = null) where T2 : ModelBase, new()
        {
            return await Db.Get<T2, V>(whereExpression);
        }

        /// <summary>
        /// 根据条件表达式获取实体列表
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public virtual async Task<List<V>> GetList<T2, V>(Expression<Func<T2, bool>> whereExpression = null) where T2 : ModelBase, new()
        {
            return await Db.GetList<T2, V>(whereExpression);
        }

        /// <summary>
        /// 根据SQL语句获取实体列表
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public virtual async Task<List<V>> GetList<T2, V>(string sql) where T2 : ModelBase, new()
        {
            return await Db.GetList<T2, V>(sql);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderByType"></param>
        /// <returns></returns>
        public virtual async Task<(List<V>, int, int)> Page<T2, V>(Expression<Func<T2, bool>> expression = null, int pageIndex = 1, int pageSize = 15,
            Expression<Func<T2, object>> orderBy = null, OrderByType orderByType = OrderByType.Asc) where T2 : ModelBase, new()
        {
            return await Db.Page<T2, V>(expression, pageIndex, pageSize, orderBy, orderByType);
        }

        /// <summary>
        /// 根据SQL分页查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <param name="orderByType"></param>
        /// <returns></returns>
        public virtual async Task<(List<V>, int, int)> Page<T2, V>(string sql = null, int pageIndex = 1, int pageSize = 15,
            Expression<Func<T2, object>> orderBy = null, OrderByType orderByType = OrderByType.Asc) where T2 : ModelBase, new()
        {
            return await Db.Page<T2, V>(sql, pageIndex, pageSize, orderBy, orderByType);
        }

        #endregion 查询3

        #region 更新

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual async Task<int> Update(T entity)
        {
            entity = SetCreaterAndUpdaterId(entity, false);
            return await Db.Update(entity);
        }

        /// <summary>
        /// 只更新不为null的字段
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual async Task<int> UpdateNotNull(T entity)
        {
            entity = SetCreaterAndUpdaterId(entity, false);
            return await Db.UpdateNotNull(entity);
        }

        /// <summary>
        /// 更新实体并指定更新与忽略的列
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="columns"></param>
        /// <param name="igcolumns"></param>
        /// <returns></returns>
        public async Task<int> Update(T entity, Expression<Func<T, object>> columns = null, Expression<Func<T, object>> igcolumns = null)
        {
            entity = SetCreaterAndUpdaterId(entity, false);
            return await Db.Update(entity, columns, igcolumns);
        }

        /// <summary>
        /// 更新实体并指定更新与忽略的列
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="columns"></param>
        /// <param name="igcolumns"></param>
        /// <returns></returns>
        public async Task<int> Update(Expression<Func<T, bool>> expression = null, Expression<Func<T, T>> columns = null, Expression<Func<T, object>> igcolumns = null)
        {
            return await Db.Update(expression, columns, igcolumns);
        }

        public async Task<int> Update(int id, Expression<Func<T, object>> columns = null, Expression<Func<T, object>> igcolumns = null)
        {
            return await Update(id, columns, igcolumns);
        }

        /// <summary>
        /// 批量更新实体并指定更新与忽略的列
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="columns"></param>
        /// <param name="igcolumns"></param>
        /// <returns></returns>
        public async Task<int> Update(List<T> entity, Expression<Func<T, object>> columns = null, Expression<Func<T, object>> igcolumns = null)
        {
            entity = SetCreaterAndUpdaterId(entity, false);
            return await Db.Update(entity, columns, igcolumns);
        }

        /// <summary>
        /// 根据SQL更新实体
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public async Task<int> Update(string sql)
        {
            return await TryExtensions.Trycatch(() => Db.Ado.ExecuteCommandAsync(sql));
        }

        #endregion 更新

        #region 更新2

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual async Task<int> Update<T2>(T2 entity) where T2 : ModelBase, new()
        {
            entity = SetCreaterAndUpdaterId(entity, false);
            return await Db.Update(entity);
        }

        /// <summary>
        /// 只更新不为null的字段
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual async Task<int> UpdateNotNull<T2>(T2 entity) where T2 : ModelBase, new()
        {
            entity = SetCreaterAndUpdaterId(entity, false);
            return await Db.UpdateNotNull(entity);
        }

        /// <summary>
        /// 更新实体并指定更新与忽略的列
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="columns"></param>
        /// <param name="igcolumns"></param>
        /// <returns></returns>
        public async Task<int> Update<T2>(T2 entity, Expression<Func<T2, object>> columns = null, Expression<Func<T2, object>> igcolumns = null) where T2 : ModelBase, new()
        {
            entity = SetCreaterAndUpdaterId(entity, false);
            return await Db.Update(entity, columns, igcolumns);
        }

        /// <summary>
        /// 更新实体并指定更新与忽略的列
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="columns"></param>
        /// <param name="igcolumns"></param>
        /// <returns></returns>
        public async Task<int> Update<T2>(Expression<Func<T2, bool>> expression = null, Expression<Func<T2, T2>> columns = null, Expression<Func<T2, object>> igcolumns = null) where T2 : ModelBase, new()
        {
            return await Db.Update(expression, columns, igcolumns);
        }

        /// <summary>
        /// 更新实体并指定更新与忽略的列
        /// </summary>
        /// <typeparam name="T2"></typeparam>
        /// <param name="id"></param>
        /// <param name="columns"></param>
        /// <param name="igcolumns"></param>
        /// <returns></returns>
        public async Task<int> Update<T2>(int id, Expression<Func<T2, T2>> columns = null, Expression<Func<T2, object>> igcolumns = null) where T2 : ModelBase, new()
        {
            return await Update(u => u.Id == id, columns, igcolumns);
        }

        /// <summary>
        /// 批量更新实体并指定更新与忽略的列
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="columns"></param>
        /// <param name="igcolumns"></param>
        /// <returns></returns>
        public async Task<int> Update<T2>(List<T2> entity, Expression<Func<T2, object>> columns = null, Expression<Func<T2, object>> igcolumns = null) where T2 : ModelBase, new()
        {
            entity = SetCreaterAndUpdaterId(entity, false);
            return await Db.Update(entity, columns, igcolumns);
        }

        #endregion 更新2

        #region 软删除

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual async Task<int> SoftDelete(int id)
        {
            return await SoftDelete(u => u.Id == id);
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <typeparam name="T2"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual async Task<int> SoftDelete<T2>(int id) where T2 : ModelBase, new()
        {
            return await SoftDelete<T2>(u => u.Id == id);
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> SoftDelete(List<int> ids)
        {
            return await SoftDelete(u => ids.Contains(u.Id));
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <typeparam name="T2"></typeparam>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> SoftDelete<T2>(List<int> ids) where T2 : ModelBase, new()
        {
            return await SoftDelete<T2>(u => ids.Contains(u.Id));
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="wherexp"></param>
        /// <returns></returns>
        public virtual async Task<int> SoftDelete(Expression<Func<T, bool>> wherexp)
        {
            var DeleterId = GetCurrentUserId();
            return await Db.SoftDelete(wherexp, DeleterId);
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <typeparam name="T2"></typeparam>
        /// <param name="wherexp"></param>
        /// <returns></returns>
        public virtual async Task<int> SoftDelete<T2>(Expression<Func<T2, bool>> wherexp) where T2 : ModelBase, new()
        {
            var DeleterId = GetCurrentUserId();
            return await Db.SoftDelete(wherexp, DeleterId);
        }

        #endregion 软删除

        /// <summary>
        /// 事务操作
        /// </summary>
        /// <param name="actions"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public virtual async Task ExecuteTransaction(params Func<Task>[] actions)
        {
            await Db.ExecuteTransaction(actions);
        }

        /// <summary>
        /// 获取当前用户Id
        /// </summary>
        /// <returns></returns>
        private int GetCurrentUserId()
        {
            return _CurrentAdmin?.Id ?? _CurrentCustomer?.Id ?? 0;
        }

        #region 创建者和更新者信息

        /// <summary>
        /// 设置创建者和更新者信息
        /// </summary>
        /// <typeparam name="T2"></typeparam>
        /// <param name="entity"></param>
        /// <param name="isCreate"></param>
        /// <returns></returns>
        private T2 SetCreaterAndUpdaterId<T2>(T2 entity, bool isCreate = true) where T2 : ModelBase
        {
            if (isCreate && entity.CreaterId == 0)
            {
                entity.CreaterId = GetCurrentUserId();
                entity.CreateTime = DateTime.Now;
            }

            entity.UpdateTime = DateTime.Now;
            entity.UpdaterId ??= GetCurrentUserId();

            return entity;
        }

        /// <summary>
        /// 设置创建者和更新者信息
        /// </summary>
        /// <typeparam name="T2"></typeparam>
        /// <param name="entities"></param>
        /// <param name="isCreate"></param>
        /// <returns></returns>
        private List<T2> SetCreaterAndUpdaterId<T2>(List<T2> entities, bool isCreate = true) where T2 : ModelBase
        {
            foreach (var entity in entities)
            {
                SetCreaterAndUpdaterId(entity, isCreate);
            }

            return entities;
        }

        #endregion 创建者和更新者信息

        //调用事务测试
        //public async Task TestExecuteTransaction()
        //{
        //    // 定义异步事务操作
        //    var actions = new Func<Task>[]
        //    {
        //() => Db.InsertAsync(new { Name = "Item1" }),
        //() => Db.UpdateAsync(new { Id = 1, Name = "UpdatedItem1" }),
        //() => Db.DeleteAsync(new { Id = 2 }),
        //    };
        //    // 调用 ExecuteTransaction 方法
        //    await ExecuteTransaction(actions);
        //}
    }
}